package com.srwl.mytx.dao;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.text.TextUtils;
import android.util.Log;

import com.srwl.mytx.greendao.DaoSession;
import com.srwl.mytx.domain.Contact;
import com.srwl.mytx.domain.InfiniteConnect;
import com.srwl.mytx.domain.Notify;
import com.srwl.mytx.domain.User;
import com.srwl.mytx.MyApplication;
import com.srwl.mytx.domain.RobotUser;
import com.srwl.mytx.domain.Topic;

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

@Deprecated
public class DemoDBManager {
    static private DemoDBManager dbMgr = new DemoDBManager();
    private DbOpenHelper dbHelper;
    private DaoSession daoSession;

    private DemoDBManager() {
       dbHelper = DbOpenHelper.getInstance(MyApplication.getInstance().getApplicationContext());

    }

    public static synchronized DemoDBManager getInstance() {
        if (dbMgr == null) {
            dbMgr = new DemoDBManager();
        }
        return dbMgr;
    }



    synchronized public void saveGoodsList(List<Topic> goodsList) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        if (db.isOpen()) {
            db.delete("goods", null, null);
            for (Topic goods : goodsList) {
                ContentValues values = new ContentValues();
                values.put("Id", goods.getId());
                values.put("name", goods.getTitle());
                values.put("auctionPrice", goods.getAuctionPrice());
                values.put("nomalPrice", goods.getPrice());
                values.put("description", goods.getContent());
                values.put("sales", goods.getSales());
                values.put("status", goods.getStatus());
                //values.put("auctionTime", goods.getStartTime());
                db.replace("goods", null, values);
            }
        }
    }

    synchronized public List<Topic> getGoodsList() {
        List<Topic> goodsList = new ArrayList<>();
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        if (db.isOpen()) {
            Cursor cursor = db.rawQuery("select * from goods" /* + " desc" */, null);
            while (cursor.moveToNext()) {
                Topic goods = new Topic();
                goods.setId(cursor.getString(cursor.getColumnIndex("Id")));
                goods.setTitle(cursor.getString(cursor.getColumnIndex("name")));
               // goods.setAuctionPrice(cursor.getInt(cursor.getColumnIndex("auctionPrice")));
              //  goods.setPrice(cursor.getInt(cursor.getColumnIndex("nomalPrice")));
                goods.setContent(cursor.getString(cursor.getColumnIndex("description")));
                goods.setSales(cursor.getInt(cursor.getColumnIndex("sales")));
                goods.setStatus(cursor.getInt(cursor.getColumnIndex("status")));
             //   goods.setStartTime(cursor.getString(cursor.getColumnIndex("auctionTime")));
                goodsList.add(goods);
            }
            cursor.close();
        }
        return goodsList;
    }


    /**
     * 保存联系人列表
     *
     * @param contactList
     */
    synchronized public void saveContactList(List<Contact> contactList) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        if (db.isOpen()) {
            db.delete(UserDao.CONTACT_TABLE_NAME, null, null);
            for (Contact contact : contactList) {
                ContentValues value = new ContentValues();
                User myUser = contact.getTargetUser();
                value.put(UserDao.COLUMN_NAME_CONTACT_ID, contact.getcId());
                value.put(UserDao.COLUMN_NAME_TARGET_USER_ID, myUser.getuId());
                value.put(UserDao.COLUMN_NAME_USER_NAME, myUser.getUsername());
                value.put(UserDao.COLUMN_NAME_GENDER, myUser.getGender());
                value.put(UserDao.COLUMN_NAME_NICK, myUser.getNick());
                value.put(UserDao.COLUMN_NAME_AVATAR, myUser.getAvatar());
                value.put(UserDao.COLUMN_NAME_PHONE, myUser.getPhone());
                value.put(UserDao.COLUMN_NAME_AREA, myUser.getArea());
               // value.put(UserDao.COLUMN_NAME_RELATION, contact.getRelation());
                value.put(UserDao.COLUMN_NAME_STATUS, contact.getStatus());
//                value.put(UserDao.COLUMN_NAME_AUTHORITY, contact.getupdateInfo());
//                value.put(UserDao.COLUMN_NAME_TARGET_AUTHORITY, contact.gettAuthority());
                value.put(UserDao.COLUMN_NAME_GROUP_NAME, contact.getGroupName());
                value.put(UserDao.COLUMN_NAME_TARGET_CONTACT_ID, contact.getcId());
                value.put(UserDao.COLUMN_NAME_INVITE_MESSAGE, contact.getInviteMessage());
                db.replace(UserDao.CONTACT_TABLE_NAME, null, value);
                List<InfiniteConnect> infiniteConnects = contact.getInfinite();
                if (infiniteConnects==null){
                    continue;
                }
                for (InfiniteConnect infiniteConnect : infiniteConnects) {
                    infiniteConnect.setcId(contact.getcId());
                    ContentValues infiniteValue = new ContentValues();
                    infiniteValue.put(UserDao.INFINITE_COLUMN_NAME_ID,infiniteConnect.getiId());
                    infiniteValue.put(UserDao.INFINITE_COLUMN_CONTACT_ID,infiniteConnect.getcId());
                    infiniteValue.put(UserDao.INFINITE_COLUMN_CONNECT_KEY,infiniteConnect.getConnectKey());
                    infiniteValue.put(UserDao.INFINITE_COLUMN_LAYER,infiniteConnect.getLayer());
                    infiniteValue.put(UserDao.INFINITE_COLUMN_AUTHORITY,infiniteConnect.getAuthority());
                    db.replace(UserDao.INFINITE_TABLE_NAME, null,infiniteValue);
                }
            }
        }
    }

    /**
     * 获取联系人列表
     *
     * @return
     */
    synchronized public List<Contact> getContactList() {
        List<Contact> contactList = new ArrayList<>();
        SQLiteDatabase db = dbHelper.getReadableDatabase();

        if (db.isOpen()) {
            Cursor cursor = db.rawQuery("select * from " + UserDao.CONTACT_TABLE_NAME
                    +" , "+ UserDao.INFINITE_TABLE_NAME
                    +" WHERE "+UserDao.CONTACT_TABLE_NAME+"."+ UserDao.COLUMN_NAME_CONTACT_ID+" = " +UserDao.INFINITE_TABLE_NAME+"."+UserDao.INFINITE_COLUMN_CONTACT_ID, null);
            while (cursor.moveToNext()) {
                Contact contact = new Contact();
                User myUser = new User();
                contact.setcId(cursor.getString(cursor.getColumnIndex(UserDao.COLUMN_NAME_CONTACT_ID)));
              //  contact.setRelation(cursor.getString(cursor.getColumnIndex(UserDao.COLUMN_NAME_RELATION)));
                contact.setStatus(cursor.getString(cursor.getColumnIndex(UserDao.COLUMN_NAME_STATUS)));
               // contact.setAuthority(cursor.getString(cursor.getColumnIndex(UserDao.COLUMN_NAME_AUTHORITY)));
               // contact.settAuthority(cursor.getString(cursor.getColumnIndex(UserDao.COLUMN_NAME_TARGET_AUTHORITY)));
                contact.setGroupName(cursor.getString(cursor.getColumnIndex(UserDao.COLUMN_NAME_GROUP_NAME)));
                contact.setcId(cursor.getString(cursor.getColumnIndex(UserDao.COLUMN_NAME_TARGET_CONTACT_ID)));
                contact.setInviteMessage(cursor.getString(cursor.getColumnIndex(UserDao.COLUMN_NAME_INVITE_MESSAGE)));
                myUser.setuId(cursor.getString(cursor.getColumnIndex(UserDao.COLUMN_NAME_TARGET_USER_ID)));
                myUser.setUsername(cursor.getString(cursor.getColumnIndex(UserDao.COLUMN_NAME_USER_NAME)));
                myUser.setGender(cursor.getInt(cursor.getColumnIndex(UserDao.COLUMN_NAME_GENDER)));
                myUser.setArea(cursor.getString(cursor.getColumnIndex(UserDao.COLUMN_NAME_AREA)));
                myUser.setNick(cursor.getString(cursor.getColumnIndex(UserDao.COLUMN_NAME_NICK)));
                myUser.setAvatar(cursor.getString(cursor.getColumnIndex(UserDao.COLUMN_NAME_AVATAR)));
                myUser.setPhone(cursor.getString(cursor.getColumnIndex(UserDao.COLUMN_NAME_PHONE)));
                contact.setTargetUser(myUser);
                contactList.add(contact);
            }
            cursor.close();
        }
        return contactList;
    }

    //当有好友增加时候  保存单个好友进数据库
    synchronized public void saveContact(Contact contact) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        if (db.isOpen()) {
            ContentValues value = new ContentValues();
            value.put(UserDao.COLUMN_NAME_CONTACT_ID, contact.getcId());
//            if (!TextUtils.isEmpty(contact.getRelation())) {
//                value.put(UserDao.COLUMN_NAME_RELATION, contact.getRelation());
//            }
            if (!TextUtils.isEmpty(contact.getStatus())) {
                value.put(UserDao.COLUMN_NAME_STATUS, contact.getStatus());
            }
//            if (!TextUtils.isEmpty(contact.getupdateInfo())) {
//                value.put(UserDao.COLUMN_NAME_AUTHORITY, contact.getupdateInfo());
//            }
//            if (!TextUtils.isEmpty(contact.gettAuthority())) {
//                value.put(UserDao.COLUMN_NAME_TARGET_AUTHORITY, contact.gettAuthority());
//            }
            if (!TextUtils.isEmpty(contact.getGroupName())) {
                value.put(UserDao.COLUMN_NAME_GROUP_NAME, contact.getGroupName());
            }
            if (!TextUtils.isEmpty(contact.getcId())) {
                value.put(UserDao.COLUMN_NAME_TARGET_CONTACT_ID, contact.getcId());
            }
            if (!TextUtils.isEmpty(contact.getInviteMessage())) {
                value.put(UserDao.COLUMN_NAME_INVITE_MESSAGE, contact.getInviteMessage());
            }
            User myUser = contact.getTargetUser();
            if (myUser != null) {
                value.put(UserDao.COLUMN_NAME_TARGET_USER_ID, myUser.getuId());
                value.put(UserDao.COLUMN_NAME_USER_NAME, myUser.getUsername());
                value.put(UserDao.COLUMN_NAME_GENDER, myUser.getGender());
                value.put(UserDao.COLUMN_NAME_NICK, myUser.getNick());
                value.put(UserDao.COLUMN_NAME_AVATAR, myUser.getAvatar());
                value.put(UserDao.COLUMN_NAME_PHONE, myUser.getPhone());
                value.put(UserDao.COLUMN_NAME_AREA, myUser.getArea());
            }
            db.replace(UserDao.CONTACT_TABLE_NAME, null, value);
        }
    }

    /**
     * 更新联系人
     * @param contact
     */
    synchronized public void updateContact(Contact contact) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        if (db.isOpen()) {
            ContentValues value = new ContentValues();
//            if (!TextUtils.isEmpty(contact.getRelation())) {
//                value.put(UserDao.COLUMN_NAME_RELATION, contact.getRelation());
//            }
            if (!TextUtils.isEmpty(contact.getStatus())) {
                value.put(UserDao.COLUMN_NAME_STATUS, contact.getStatus());
            }
//            if (!TextUtils.isEmpty(contact.getupdateInfo())) {
//                value.put(UserDao.COLUMN_NAME_AUTHORITY, contact.getupdateInfo());
//            }
//            if (!TextUtils.isEmpty(contact.gettAuthority())) {
//                value.put(UserDao.COLUMN_NAME_TARGET_AUTHORITY, contact.gettAuthority());
//            }
            if (!TextUtils.isEmpty(contact.getGroupName())) {
                value.put(UserDao.COLUMN_NAME_GROUP_NAME, contact.getGroupName());
            }
            if (!TextUtils.isEmpty(contact.getcId())) {
                value.put(UserDao.COLUMN_NAME_TARGET_CONTACT_ID, contact.getcId());
            }
            if (!TextUtils.isEmpty(contact.getInviteMessage())) {
                value.put(UserDao.COLUMN_NAME_INVITE_MESSAGE, contact.getInviteMessage());
            }
            User myUser = contact.getTargetUser();
            if (myUser != null) {
                value.put(UserDao.COLUMN_NAME_TARGET_USER_ID, myUser.getuId());
                value.put(UserDao.COLUMN_NAME_USER_NAME, myUser.getUsername());
                value.put(UserDao.COLUMN_NAME_GENDER, myUser.getGender());
                value.put(UserDao.COLUMN_NAME_NICK, myUser.getNick());
                value.put(UserDao.COLUMN_NAME_AVATAR, myUser.getAvatar());
                value.put(UserDao.COLUMN_NAME_PHONE, myUser.getPhone());
                value.put(UserDao.COLUMN_NAME_AREA, myUser.getArea());
            }

            db.update(UserDao.CONTACT_TABLE_NAME, value, UserDao.COLUMN_NAME_CONTACT_ID + " = ?", new String[]{contact.getcId()});
        }

    }

    /**
     * @param id 联系人Id
     */
    synchronized public void deleteContact(String id) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        if (db.isOpen()) {
            db.delete("contact", UserDao.COLUMN_NAME_CONTACT_ID + "= ?", new String[]{id});
        }
    }


    public void setDisabledGroups(List<String> groups) {
        setList(UserDao.COLUMN_NAME_DISABLED_GROUPS, groups);
    }

    public List<String> getDisabledGroups() {
        return getList(UserDao.COLUMN_NAME_DISABLED_GROUPS);
    }

    public void setDisabledIds(List<String> ids) {
        setList(UserDao.COLUMN_NAME_DISABLED_IDS, ids);
    }

    public List<String> getDisabledIds() {
        return getList(UserDao.COLUMN_NAME_DISABLED_IDS);
    }

    synchronized private void setList(String column, List<String> strList) {
        StringBuilder strBuilder = new StringBuilder();

        for (String hxid : strList) {
            strBuilder.append(hxid).append("$");
        }

        SQLiteDatabase db = dbHelper.getWritableDatabase();
        if (db.isOpen()) {
            ContentValues values = new ContentValues();
            values.put(column, strBuilder.toString());

            db.update(UserDao.PREF_TABLE_NAME, values, null, null);
        }
    }

    synchronized private List<String> getList(String column) {
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        Cursor cursor = db.rawQuery("getImageInfo " + column + " from " + UserDao.PREF_TABLE_NAME, null);
        if (!cursor.moveToFirst()) {
            cursor.close();
            return null;
        }

        String strVal = cursor.getString(0);
        if (strVal == null || strVal.equals("")) {
            return null;
        }

        cursor.close();

        String[] array = strVal.split("$");

        if (array != null && array.length > 0) {
            List<String> list = new ArrayList<String>();
            for (String str : array) {
                list.add(str);
            }

            return list;
        }

        return null;
    }

    /**
     * save a message
     *
     * @param message
     * @return return cursor of the message
     */
    public synchronized Integer saveMessage(Notify message) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        if (db.isDbLockedByCurrentThread()) {
            Log.e("DBManager:", "数据库被锁定");
        }
        int id = -1;
        if (db.isOpen()) {
            // db.beginTransaction();
            ContentValues values = new ContentValues();
           // User contactUser = message.getUser();
            values.put(InviteMessgeDao.COLUMN_NAME_OBJECT_ID, message.getId());
            values.put(InviteMessgeDao.COLUMN_NAME_GROUP_ID, message.getGroupId());
            values.put(InviteMessgeDao.COLUMN_NAME_GROUP_Name, message.getGroupName());
            values.put(InviteMessgeDao.COLUMN_NAME_REASON, message.getContent());
          //  values.put(InviteMessgeDao.COLUMN_NAME_REALATION, message.getRelation());
         //   values.put(InviteMessgeDao.COLUMN_NAME_TIME, message.getCreated());
            values.put(InviteMessgeDao.COLUMN_NAME_STATUS, message.getStatus());
            values.put(InviteMessgeDao.COLUMN_NAME_GROUPINVITER, message.getGroupInviter());
          //  values.put(InviteMessgeDao.COLUMN_NAME_TARGET_CONTACT_ID, message.gettCid());
        //    values.put(InviteMessgeDao.COLUMN_NAME_CONTACT_ID, message.getcId());
//            values.put(InviteMessgeDao.COLUMN_NAME_FROM, contactUser.getuId());
//            values.put(InviteMessgeDao.COLUMN_NAME_AVATAR, contactUser.getAvatar());
//            values.put(InviteMessgeDao.COLUMN_NAME_NICK, contactUser.getTitle());
//            values.put(InviteMessgeDao.COLUMN_NAME_SEX, contactUser.getGender());
//            values.put(InviteMessgeDao.COLUMN_NAME_AREA, contactUser.getArea());

            db.insert(InviteMessgeDao.TABLE_NAME, null, values);
            //db.setTransactionSuccessful();
            Cursor cursor = db.rawQuery("select last_insert_rowid() from " + InviteMessgeDao.TABLE_NAME, null);
            if (cursor.moveToFirst()) {
                id = cursor.getInt(0);
            }

            cursor.close();
        }

        return id;
    }

    /**
     * update message
     *
     * @param msgId
     * @param values
     */
    synchronized public void updateMessage(String msgId, ContentValues values) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        if (db.isOpen()) {
            db.update(InviteMessgeDao.TABLE_NAME, values, InviteMessgeDao.COLUMN_NAME_OBJECT_ID + " = ?", new String[]{String.valueOf(msgId)});
        }

    }

    /**
     * get messges
     *
     * @return
     */
    synchronized public List<Notify> getMessagesList() {
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        List<Notify> msgs = new ArrayList<Notify>();
        if (db.isOpen()) {
            Cursor cursor = db.rawQuery("select * from " + InviteMessgeDao.TABLE_NAME/* + " desc" */, null);
            while (cursor.moveToNext()) {
                Notify msg = new Notify();
                String Id = cursor.getString(cursor.getColumnIndex(InviteMessgeDao.COLUMN_NAME_OBJECT_ID));
                String from = cursor.getString(cursor.getColumnIndex(InviteMessgeDao.COLUMN_NAME_FROM));
                String groupid = cursor.getString(cursor.getColumnIndex(InviteMessgeDao.COLUMN_NAME_GROUP_ID));
                String groupname = cursor.getString(cursor.getColumnIndex(InviteMessgeDao.COLUMN_NAME_GROUP_Name));
                String reason = cursor.getString(cursor.getColumnIndex(InviteMessgeDao.COLUMN_NAME_REASON));
                String realation = cursor.getString(cursor.getColumnIndex(InviteMessgeDao.COLUMN_NAME_REALATION));
               // msg.setcId(cursor.getString(cursor.getColumnIndex(InviteMessgeDao.COLUMN_NAME_CONTACT_ID)));
              //  msg.settCid(cursor.getString(cursor.getColumnIndex(InviteMessgeDao.COLUMN_NAME_TARGET_CONTACT_ID)));
                long time = cursor.getLong(cursor.getColumnIndex(InviteMessgeDao.COLUMN_NAME_TIME));
                int status = cursor.getInt(cursor.getColumnIndex(InviteMessgeDao.COLUMN_NAME_STATUS));
                String groupInviter = cursor.getString(cursor.getColumnIndex(InviteMessgeDao.COLUMN_NAME_GROUPINVITER));
                msg.setId(Id);
                User user = new User();
                user.setuId(from);
                //  msg.setid(from);
                msg.setGroupId(groupid);
                msg.setGroupName(groupname);
                msg.setContent(reason);
               // msg.setRelation(realation);
              //  msg.setCreated(time);
                msg.setGroupInviter(groupInviter);
                user.setArea(cursor.getString(cursor.getColumnIndex(InviteMessgeDao.COLUMN_NAME_AREA)));
                user.setGender(cursor.getInt(cursor.getColumnIndex(InviteMessgeDao.COLUMN_NAME_SEX)));
                user.setNick(cursor.getString(cursor.getColumnIndex(InviteMessgeDao.COLUMN_NAME_NICK)));
                user.setAvatar(cursor.getString(cursor.getColumnIndex(InviteMessgeDao.COLUMN_NAME_AVATAR)));
                //msg.setUser(user);
                //群组相关的邀请信息
//                if (status == InviteMesageStatus.BEINVITEED.ordinal())
//                    msg.setStatus(InviteMesageStatus.BEINVITEED);
//                else if (status == InviteMesageStatus.BEAGREED.ordinal())
//                    msg.setStatus(InviteMesageStatus.BEAGREED);
//                else if (status == InviteMesageStatus.BEREFUSED.ordinal())
//                    msg.setStatus(InviteMesageStatus.BEREFUSED);
//                else if (status == InviteMesageStatus.AGREED.ordinal())
//                    msg.setStatus(InviteMesageStatus.AGREED);
//                else if (status == InviteMesageStatus.REFUSED.ordinal())
//                    msg.setStatus(InviteMesageStatus.REFUSED);
//                else if (status == InviteMesageStatus.BEAPPLYED.ordinal())
//                    msg.setStatus(InviteMesageStatus.BEAPPLYED);
//                else if (status == InviteMesageStatus.GROUPINVITATION.ordinal())
//                    msg.setStatus(InviteMesageStatus.GROUPINVITATION);
//                else if (status == InviteMesageStatus.GROUPINVITATION_ACCEPTED.ordinal())
//                    msg.setStatus(InviteMesageStatus.GROUPINVITATION_ACCEPTED);
//                else if (status == InviteMesageStatus.GROUPINVITATION_DECLINED.ordinal())
//                    msg.setStatus(InviteMesageStatus.GROUPINVITATION_DECLINED);
//                else if (status == InviteMesageStatus.BE_AGREED_NOT_SAVE.ordinal())
//                    msg.setStatus(InviteMesageStatus.BE_AGREED_NOT_SAVE);
//                else if (status == InviteMesageStatus.BESAVED.ordinal())
//                    msg.setStatus(InviteMesageStatus.BESAVED);
                msg.setStatus(new Integer(status));
                msgs.add(msg);
            }
            cursor.close();
        }

        return msgs;
    }

    /**
     * delete invitation message
     *
     * @param from
     */
    synchronized public void deleteMessage(String from) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        if (db.isOpen()) {
            db.delete(InviteMessgeDao.TABLE_NAME, InviteMessgeDao.COLUMN_NAME_FROM + " = ?", new String[]{from});
        }

    }

    synchronized public void deleteAllNoticeMessage() {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        if (db.isOpen()) {
            db.delete(InviteMessgeDao.TABLE_NAME, null, null);
        }

    }

    synchronized int getUnreadNotifyCount() {
        int count = 0;
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        if (db.isOpen()) {
            Cursor cursor = db.rawQuery("select " + InviteMessgeDao.COLUMN_NAME_UNREAD_MSG_COUNT + " from " + InviteMessgeDao.TABLE_NAME, null);
            if (cursor.moveToFirst()) {
                count = cursor.getInt(0);
            }
            cursor.close();
        }

        return count;
    }


    synchronized void setUnreadNotifyCount(int count) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        if (db.isOpen()) {
            ContentValues values = new ContentValues();
            values.put(InviteMessgeDao.COLUMN_NAME_UNREAD_MSG_COUNT, count);

            db.update(InviteMessgeDao.TABLE_NAME, values, null, null);
        }

    }

    synchronized public void closeDB() {
        if (dbHelper != null) {
            dbHelper.closeDB();
        }
        dbMgr = null;
    }


    /**
     * Save Robot list
     */
    synchronized public void saveRobotList(List<RobotUser> robotList) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        if (db.isOpen()) {
            db.delete(UserDao.ROBOT_TABLE_NAME, null, null);
            for (RobotUser item : robotList) {
                ContentValues values = new ContentValues();
                values.put(UserDao.ROBOT_COLUMN_NAME_ID, item.getUsername());
                if (item.getNick() != null)
                    values.put(UserDao.ROBOT_COLUMN_NAME_NICK, item.getNick());
                if (item.getAvatar() != null)
                    values.put(UserDao.ROBOT_COLUMN_NAME_AVATAR, item.getAvatar());
                db.replace(UserDao.ROBOT_TABLE_NAME, null, values);
            }
        }
    }

    /**
     * load robot list
     */
    synchronized public Map<String, RobotUser> getRobotList() {
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        Map<String, RobotUser> users = null;
        if (db.isOpen()) {
            Cursor cursor = db.rawQuery("select * from " + UserDao.ROBOT_TABLE_NAME, null);
            if (cursor.getCount() > 0) {
                users = new Hashtable<String, RobotUser>();
            }
            ;
            while (cursor.moveToNext()) {
                String username = cursor.getString(cursor.getColumnIndex(UserDao.ROBOT_COLUMN_NAME_ID));
                String nick = cursor.getString(cursor.getColumnIndex(UserDao.ROBOT_COLUMN_NAME_NICK));
                String avatar = cursor.getString(cursor.getColumnIndex(UserDao.ROBOT_COLUMN_NAME_AVATAR));
                RobotUser user = new RobotUser(username);
                user.setNick(nick);
                user.setAvatar(avatar);
                String headerName = null;
                if (!TextUtils.isEmpty(user.getNick())) {
                    headerName = user.getNick();
                } else {
                    headerName = user.getUsername();
                }
                if (Character.isDigit(headerName.charAt(0))) {
                    user.setInitialLetter("#");
                } else {
//                    user.setInitialLetter(HanziToPinyin.getInstance().get(headerName.substring(0, 1)).get(0).target
//                            .substring(0, 1).toUpperCase());
//                    char header = user.getInitialLetter().toLowerCase().charAt(0);
//                    if (header < 'a' || header > 'z') {
//                        user.setInitialLetter("#");
//                    }
                }

                users.put(username, user);
            }
            cursor.close();
        }
        return users;
    }
}
